<!-- //#region Template -->
<template>
  <div class="bom-page">
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" label-width="90px" @submit.prevent>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="成品编码">
              <el-input v-model="searchForm.productCode" placeholder="请输入成品编码" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="成品名称">
              <el-input v-model="searchForm.productName" placeholder="请输入成品名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="物料版本">
              <el-input v-model="searchForm.bomCode" placeholder="请输入BOM物料版本" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="end" :gutter="12">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" class="search-actions">
            <el-space wrap>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-space>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <div class="title">BOM成品清单</div>
        <div class="actions">
          <el-button type="primary" @click="handleAdd">新增成品</el-button>
          <el-tag size="small" effect="light">共 {{ page.Totalcount }} 条</el-tag>
        </div>
      </div>

      <el-table :data="tableData" border style="width: 100%" height="520" header-row-class-name="table-header" class="bom-table">
        <el-table-column fixed="left" type="index" label="序号" width="80" align="center" />
        <el-table-column prop="itemcode" label="成品编码" width="150" align="center" />
        <el-table-column prop="goodsname" label="成品名称" width="180" align="center" />
        <el-table-column prop="version" label="版本号" width="100" align="center" />
        <el-table-column prop="spec" label="规格" width="150" align="center" />
        <el-table-column prop="unit" label="单位" width="100" align="center" />
        <el-table-column prop="number" label="数量" width="100" align="center" />
        <el-table-column prop="isUse" label="是否启用" width="120" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.isUse == true" type="success">启用</el-tag>
            <el-tag v-else type="info">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column fixed="right" label="操作" width="250" align="center">
          <template #default="{ row }">
            <el-space>
              <el-button type="primary" link @click="handleView(row)">详情</el-button>
              <el-button type="warning" link @click="handleEdit(row)">修改</el-button>
              <el-button 
                v-if="row.isUse" 
                type="danger" 
                link 
                @click="handleDisable(row)">
                停用
              </el-button>
              <el-button 
                v-else 
                type="success" 
                link 
                @click="handleEnable(row)">
                启用
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination v-model:current-page="page.Pageindex" v-model:page-size="page.Pagesize" :page-sizes="[5,10, 20, 30, 50]"
          background layout="total, sizes, prev, pager, next, jumper" :total="page.Totalcount"
         />
      </div>
    </el-card>

    <!-- 添加/修改对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose">
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="formRules" 
        label-width="100px">
        <el-form-item label="成品编码" prop="itemcode">
          <el-input 
            v-model="formData.itemcode" 
            placeholder="请输入成品编码" 
            :disabled="isEdit"
            clearable />
        </el-form-item>
        <el-form-item label="成品名称" prop="goodsname">
          <el-input 
            v-model="formData.goodsname" 
            placeholder="请输入成品名称" 
            clearable />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="spec">
              <el-input 
                v-model="formData.spec" 
                placeholder="请输入规格型号" 
                clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input 
                v-model="formData.unit" 
                placeholder="请输入单位（个、米、千克等）" 
                clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-input 
                v-model="formData.version" 
                placeholder="请输入版本号" 
                clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="number">
              <el-input-number 
                v-model="formData.number" 
                :min="1" 
                :max="999999"
                placeholder="请输入数量"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否启用" prop="isUse">
          <el-switch 
            v-model="formData.isUse" 
            active-text="启用" 
            inactive-text="停用" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="formData.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注" 
            clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<!-- //#endregion Template -->
<script setup lang="ts">
//#region Imports
import myaxios from '@/Http/http'
import { onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
//#endregion

//#region State
const router = useRouter()  //页面跳转
const tableData = ref([])  //表格数据
const formRef = ref<FormInstance>()  //表单引用
const dialogVisible = ref(false)  //对话框显示状态
const isEdit = ref(false)  //是否为编辑模式
const submitLoading = ref(false)  //提交加载状态
const dialogTitle = ref('新增成品')  //对话框标题

// 分页信息
const page = reactive({
  Pageindex: 1,
  Pagesize: 5,
  Totalcount: 0
})

// 查询表单
const searchForm = reactive({
  productCode: '',  // 成品编码 -> Itemcode
  productName: '',  // 成品名称 -> GoodsName
  bomCode: '',      // BOM编号 -> BOMNumber
  status: '' as boolean | ''  // 状态 -> IsUse (true-启用, false-禁用)
})

// 状态选项
const statusOptions: Array<{ label: string; value: boolean | '' }> = [
  { label: '全部', value: '' },
  { label: '启用', value: true },
  { label: '禁用', value: false }
]

// 加载数据
const LoadData = () => {
  myaxios.get('/api/BOMs/GetBOM', {
    params: {
      Pageindex: page.Pageindex,
      Pagesize: page.Pagesize,
      Itemcode: searchForm.productCode || undefined,
      GoodsName: searchForm.productName || undefined,
      BOMNumber: searchForm.bomCode || undefined,
      IsUse: searchForm.status !== '' ? searchForm.status : undefined
    }
  }).then(res => {
    console.log(res.data)
    tableData.value = res.data.listResult || []
    page.Totalcount = res.data.totalcount || 0
  }).catch(err => {
    console.error('获取BOM列表失败:', err)
    tableData.value = []
    page.Totalcount = 0
  })
}

// 查询事件
const handleSearch = () => {
  page.Pageindex = 1
  LoadData()
}

// 重置事件
const handleReset = () => {
  searchForm.productCode = ''
  searchForm.productName = ''
  searchForm.bomCode = ''
  searchForm.status = ''
  page.Pageindex = 1
  LoadData()
}

//#region Watchers & Lifecycle
// 监听分页变化
watch(
  () => [page.Pageindex, page.Pagesize],
  () => {
    LoadData()
  }
)

onMounted(() => {
  LoadData()
})
//#endregion

type BomStatus = 'draft' | 'enabled' | 'disabled'
interface BomItem {
  id: number
  bomCode: string
  productCode: string
  productName: string
  version: string
  status: BomStatus
  updatedAt: string
  owner: string
  remark: string
}


// 表单数据
const formData = reactive({
  id: 0,
  itemcode: '',  // 成品编码
  goodsname: '',  // 成品名称
  spec: '',  // 规格型号
  unit: '',  // 单位
  version: '1.0V',  // 版本号
  number: 1,  // 数量
  remark: '',  // 备注
  isUse: true  // 是否启用
})

// 表单验证规则
const formRules: FormRules = {
  itemcode: [
    { required: true, message: '请输入成品编码', trigger: 'blur' }
  ],
  goodsname: [
    { required: true, message: '请输入成品名称', trigger: 'blur' }
  ],
  number: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ]
}
//#endregion

//#region Methods
// 重置表单数据
const resetFormData = () => {
  formData.id = 0
  formData.itemcode = ''
  formData.goodsname = ''
  formData.spec = ''
  formData.unit = ''
  formData.version = '1.0V'
  formData.number = 1
  formData.remark = ''
  formData.isUse = true
  formRef.value?.clearValidate()
}

// 新增成品
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增成品'
  resetFormData()
  dialogVisible.value = true
}

// 修改成品
const handleEdit = (row: any) => {
  isEdit.value = true
  dialogTitle.value = '修改成品'
  formData.id = row.id
  formData.itemcode = row.itemcode || ''
  formData.goodsname = row.goodsname || ''
  formData.spec = row.spec || ''
  formData.unit = row.unit || ''
  formData.version = row.version || '1.0V'
  formData.number = row.number || 1
  formData.remark = row.remark || ''
  formData.isUse = row.isUse !== undefined ? row.isUse : true
  formRef.value?.clearValidate()
  dialogVisible.value = true
}

// 停用成品
const handleDisable = (row: any) => {
  ElMessageBox.confirm(
    `确定要停用成品"${row.goodsname}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    submitDisable(row.id, true)
  }).catch(() => {
    // 用户取消操作
  })
}

// 启用成品
const handleEnable = (row: any) => {
  ElMessageBox.confirm(
    `确定要启用成品"${row.goodsname}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    submitDisable(row.id, false)
  }).catch(() => {
    // 用户取消操作
  })
}

// 提交停用/启用
const submitDisable = async (id: number, isDisable: boolean) => {
  try {
    const currentUserName = localStorage.getItem('realname') || '系统'
    const res = await myaxios.put('/api/BOMs/DisableProductBOM', {
      id: id,
      isDisable: isDisable,
      currentUserName: currentUserName
    })
    
    if (res.data.code === 200) {
      ElMessage.success(res.data.message || (isDisable ? '停用成功' : '启用成功'))
      LoadData()  // 刷新列表
    } else {
      ElMessage.error(res.data.message || (isDisable ? '停用失败' : '启用失败'))
    }
  } catch (err: any) {
    console.error('停用/启用失败:', err)
    ElMessage.error(err.response?.data?.message || (isDisable ? '停用失败' : '启用失败'))
  }
}

// 提交表单（新增/修改）
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      const currentUserName = localStorage.getItem('realname') || '系统'
      
      if (isEdit.value) {
        // 修改
        myaxios.put('/api/BOMs/UpdateProductBOM', {
          id: formData.id,
          itemcode: formData.itemcode,
          goodsname: formData.goodsname,
          spec: formData.spec,
          unit: formData.unit,
          version: formData.version,
          number: formData.number,
          remark: formData.remark,
          isUse: formData.isUse,
          currentUserName: currentUserName
        }).then(res => {
          submitLoading.value = false
          if (res.data.code === 200) {
            ElMessage.success(res.data.message || '修改成功')
            dialogVisible.value = false
            LoadData()  // 刷新列表
          } else {
            ElMessage.error(res.data.message || '修改失败')
          }
        }).catch(err => {
          submitLoading.value = false
          console.error('修改失败:', err)
          ElMessage.error(err.response?.data?.message || '修改失败')
        })
      } else {
        // 新增
        myaxios.post('/api/BOMs/CreateProductBOM', {
          itemcode: formData.itemcode,
          goodsname: formData.goodsname,
          spec: formData.spec,
          unit: formData.unit,
          version: formData.version,
          number: formData.number,
          remark: formData.remark,
          isUse: formData.isUse,
          currentUserName: currentUserName
        }).then(res => {
          submitLoading.value = false
          if (res.data.code === 200) {
            ElMessage.success(res.data.message || '新增成功')
            dialogVisible.value = false
            LoadData()  // 刷新列表
          } else {
            ElMessage.error(res.data.message || '新增失败')
          }
        }).catch(err => {
          submitLoading.value = false
          console.error('新增失败:', err)
          ElMessage.error(err.response?.data?.message || '新增失败')
        })
      }
    } else {
      ElMessage.warning('请填写完整的表单信息')
    }
  })
}

// 对话框关闭事件
const handleDialogClose = () => {
  resetFormData()
  formRef.value?.clearValidate()
}

// 查看详情
const handleView = (row: any) => {
  router.push({
    path: '/BOMDetails',
    query: {
      itemcode: row.itemcode,
      version: row.version,
      id: row.id
    }
  })
}
//#endregion
</script>

<!-- //#region Style -->
<style scoped>
.bom-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.search-card,
.table-card {
  border-radius: 8px;
}

.search-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.table-toolbar .title {
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

.table-toolbar .actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
}

.table-header {
  background-color: #f0f2f5 !important;
  color: #1d2129;
  font-weight: 600;
}

/* 表格滚动条样式优化 */
.bom-table {
  overflow-x: auto;
}

.bom-table :deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

.bom-table :deep(.el-table__body) {
  width: 100%;
}

/* 确保表格单元格内容居中 */
.bom-table :deep(.el-table td),
.bom-table :deep(.el-table th) {
  text-align: center;
}
</style>
<!-- //#endregion Style -->
